﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.Roles;
using B.S.Meeting.ReadAPI.Dtos;
using B.S.Meeting.ReadAPI.Filter;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace B.S.Meeting.ReadAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class RoleController : ControllerBase
    {
        IBaseRepository<Role> rRep;
        IMediator mediator;
        ILogger<RoleController> logger;
        public RoleController(IMediator mediator, ILogger<RoleController> logger, IBaseRepository<Role> rRep)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.rRep = rRep;
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaging<List<RoleDto>>>> GetRole([FromQuery] GetRoleCommand cmd)
        {
            try
            {
                var result = await mediator.Send(cmd);  
                return result;  
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 导出角色信息
        /// </summary>
        /// <param name="roleDto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<IActionResult> ExportRoleExcel()
        {
            try
            {
                // 通过中介者获取角色列表
                var roles = rRep.GetAll().ToList();

                // 调用ExcelExporter导出
                var excelBytes = ExcelExporter.ExportToExcel(roles, "角色列表");

                // 返回Excel文件
                return File(
                    excelBytes,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "角色列表.xlsx"
                );
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
